package com.onenine.app.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.onenine.app.R;
import com.onenine.app.utils.CHelper;
import com.onenine.base.base.BaseActivity;
import com.onenine.base.utils.StatusBarUtils;
import com.onenine.base.utils.Toasty;
import com.onenine.base.view.CircleIndicatorView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class BrowserImageActivity extends BaseActivity {

    //该名字不可乱更改，其它地方如NineGridImageView也使用到该名称
    public static final String IMAGE_TRANSITION_NAME = "share";
    public static final String BURN = "BURN";
    public static final String IMAGE_URL = "IMAGE_URL";
    public static final String IMAGE_URLS = "IMAGE_URLS";
    public static final String IMG_POSITION = "IMG_POSITION";
    public static final String IMG_CURRENT_POSITION = "IMG_CURRENT_POSITION";
    public static final String MSG_ID = "MSG_ID";
    private RecyclerView rvPreview;
    private CircleIndicatorView mIndicatorView;
    private List<String> imgList = new ArrayList<>();
    private PagerSnapHelper snapHelper;
    private ImgAdapter imgAdapter;
    private int enterPosition, currentPosition;

    /**
     * 加载单图
     *
     * @param context
     * @param imageUrl
     */
    public static void launchActivity(Context context, String imageUrl) {
        Intent intent = new Intent(context, BrowserImageActivity.class);
        intent.putExtra(IMAGE_URL, imageUrl);
        context.startActivity(intent);
    }

    /**
     * 加载单图，共享元素动画
     *
     * @param activity
     * @param shareView
     * @param imageUrl
     */
    public static void launchActivity(Activity activity, View shareView, String imageUrl) {
        Intent intent = new Intent(activity, BrowserImageActivity.class);
        intent.putExtra(IMAGE_URL, imageUrl);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            activity.startActivity(intent);
        } else {
            ActivityOptionsCompat options = ActivityOptionsCompat.
                    makeSceneTransitionAnimation(activity, shareView, IMAGE_TRANSITION_NAME);
            activity.startActivity(intent, options.toBundle());
        }
    }

    /**
     * 加载指定初始位置的多图
     *
     * @param context
     * @param imageUrlList
     * @param initPos
     */
    public static void launchActivity(Context context, ArrayList<String> imageUrlList, int initPos) {
        Intent intent = new Intent(context, BrowserImageActivity.class);
        intent.putExtra(IMAGE_URLS, imageUrlList);
        intent.putExtra(IMG_POSITION, initPos);
        context.startActivity(intent);
    }

    /**
     * 加载指定初始位置的多图,共享元素
     *
     * @param activity
     * @param shareView
     * @param imageUrlList
     * @param initPos
     */
    public static void launchActivity(Activity activity, View shareView, List<String> imageUrlList, int initPos) {
        Intent intent = new Intent(activity, BrowserImageActivity.class);
        intent.putExtra(IMAGE_URLS, (Serializable) imageUrlList);
        intent.putExtra(IMG_POSITION, initPos);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            activity.startActivity(intent);
        } else {
            ActivityOptionsCompat options = ActivityOptionsCompat.
                    makeSceneTransitionAnimation(activity, shareView, IMAGE_TRANSITION_NAME);
            activity.startActivity(intent, options.toBundle());
        }
    }

    /**
     * 加载多图
     *
     * @param context
     * @param imageUrlList
     */
    public static void launchActivity(Context context, ArrayList<String> imageUrlList) {
        launchActivity(context, imageUrlList, 0);
    }

    /**
     * 加载阅兵即焚单图
     *
     * @param activity
     * @param msgId
     * @param imageUrl
     * @param isBurn
     * @param reqCode
     */
    public static void launchActivityForResult(Activity activity, int msgId, String imageUrl, boolean isBurn, int reqCode) {
        Intent intent = new Intent(activity, BrowserImageActivity.class);
        intent.putExtra(BURN, isBurn);
        intent.putExtra(IMAGE_URL, imageUrl);
        intent.putExtra(MSG_ID, msgId);
        activity.startActivityForResult(intent, reqCode);
    }

    /**
     * 加载阅兵即焚单图
     *
     * @param activity
     * @param msgId
     * @param imageUrl
     * @param isBurn
     * @param reqCode
     */
    public static void launchActivityForResult(Activity activity, View shareView, int msgId, String imageUrl, boolean isBurn, int reqCode) {
        Intent intent = new Intent(activity, BrowserImageActivity.class);
        intent.putExtra(BURN, isBurn);
        intent.putExtra(IMAGE_URL, imageUrl);
        intent.putExtra(MSG_ID, msgId);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            activity.startActivity(intent);
        } else {
            ActivityOptionsCompat options = ActivityOptionsCompat.
                    makeSceneTransitionAnimation(activity, shareView, IMAGE_TRANSITION_NAME);
            activity.startActivityForResult(intent, reqCode, options.toBundle());
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        StatusBarUtils.setTransparent(this);
        supportPostponeEnterTransition();
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_image_browser;
    }

    @Override
    protected void initViews() {
        super.initViews();
        initVars();
        initView();
    }

    private void initView() {
        rvPreview = findViewById(R.id.rv_preview);
        mIndicatorView = findViewById(R.id.civ_indicator);
        mIndicatorView.setVisibility(imgList.size() > 1 ? View.VISIBLE : View.GONE);
        snapHelper = new PagerSnapHelper() {
            @Override
            public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
                int position = super.findTargetSnapPosition(layoutManager, velocityX, velocityY);
                if (position > -1 && position < imgList.size()) {
                    currentPosition = position;
                    mIndicatorView.playTo(imgList.size(), currentPosition);
                }
                return currentPosition;
            }
        };
        snapHelper.attachToRecyclerView(rvPreview);
        imgAdapter = new ImgAdapter(imgList);
        rvPreview.setLayoutManager(new LinearLayoutManager(this
                , LinearLayoutManager.HORIZONTAL, false));
        rvPreview.setAdapter(imgAdapter);
        imgAdapter.bindToRecyclerView(rvPreview);
        rvPreview.scrollToPosition(enterPosition);
        mIndicatorView.playTo(imgList.size(), currentPosition);
    }

    private void initVars() {
        String imagePath = getIntent().getStringExtra(IMAGE_URL);
        if (imagePath != null) {
            imgList.add(imagePath);
        } else {
            ArrayList<String> imageUrls = (ArrayList<String>) getIntent().getSerializableExtra(IMAGE_URLS);
            if (imageUrls != null) {
                imgList.addAll(imageUrls);
            }
            enterPosition = getIntent().getIntExtra(IMG_POSITION, 0);
            currentPosition = enterPosition;
        }
    }

    @Override
    protected void setStatusBarStyle() {
    }

    class ImgAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
        public ImgAdapter(List<String> list) {
            super(R.layout.layout_photo_view, list);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            final ImageView iv_img = helper.getView(R.id.iv_img);
            helper.setVisible(R.id.pb_loading, true);
            iv_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
            Glide.with(mContext).load(CHelper.getFullPlatformOriginImageUrl(item)).listener(new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    Toasty.showNormal(R.string.image_download_failure_format);
                    supportStartPostponedEnterTransition();
                    helper.setVisible(R.id.pb_loading, false);
                    finish();
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                    supportStartPostponedEnterTransition();
                    helper.setVisible(R.id.pb_loading, false);
                    return false;
                }
            }).into(iv_img);
        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (enterPosition != currentPosition) {
            //滑动过，需要刷新
            final View exitView = imgAdapter.getViewByPosition(currentPosition, R.id.iv_img);
            ActivityCompat.setEnterSharedElementCallback(this, new android.support.v4.app.SharedElementCallback() {
                @Override
                public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
                    names.clear();
                    sharedElements.clear();
                    names.add(ViewCompat.getTransitionName(exitView));
                    sharedElements.put(ViewCompat.getTransitionName(exitView), exitView);

                }
            });
        }
    }

    @Override
    public void finishAfterTransition() {
        Intent intent = new Intent();
        if (enterPosition == currentPosition) {
            //没有改变
            intent.putExtra(IMG_CURRENT_POSITION, -1);
        } else {
            intent.putExtra(IMG_CURRENT_POSITION, currentPosition);
        }
        setResult(RESULT_OK, intent);
        super.finishAfterTransition();
    }

}
